package com.hdy.javachatroomdemo.Service;

import com.hdy.javachatroomdemo.Model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class FriendService {
    @Autowired
    FriendMapper friendMapper;
    public List<Friend> friendList(User user) {
        //预防查询数据库时报错
        List<Friend>friendList=null;
        try{
            friendList=friendMapper.selectAllFriend(user);
            if(friendList==null || friendList.size()==0){
                //没有好友,返回包含一个空对象的列表用于前端判断
                List<Friend> ret=new ArrayList<Friend>();
                ret.add(new Friend());
                return ret;
            }

        }catch(Exception e){
            e.printStackTrace();
        }
        return friendList;
    }


    public List<Friend> queryFriend(String friendName,String username,Integer userId) {
        //这里要把查询人排除在外,在数据库中查询的时候就排除
        //还有一个问题,已经添加过的好友也应该要排除
        List<Friend> ret= friendMapper.queryFriendByUserName(friendName,username,userId);
        //这里查询好友可以为空,所以直接返回结果就行
        return ret;
    }

    public List<MessageResponse> queryFriendRequest2(Integer userId){
        //查询历史添加好友消息可以为空,所以直接返回
         return friendMapper.queryFriendRequest2(userId);
    }

    public int deleteFriendRequest(MessageRequest messageRequest) {
       int ret= friendMapper.deleteFriendRequest(messageRequest);
        System.out.println("删除添加好友请求成功,影响行数:"+ret);
        return ret;
    }

    public void addFriend(MessageRequest messageRequest) {
        //这里要注意,如果好友关系已经存在,则不能添加
        //所以先判断
        List<MessageResponse> retExists= friendMapper.queryFriendExists(messageRequest);
        if(retExists.size()>0){
            System.out.println("好友关系已经存在 friendId:"+retExists.get(0).getFriendId()+
            "userId:"+retExists.get(0).getFromId());
            return;
        }
        int ret=friendMapper.addFriend(messageRequest);
        System.out.println("添加好友关系成功 user_id:"+messageRequest.getUserId()+
                " friend_id:"+messageRequest.getFriendId()+" 影响行数:"+ret);
    }
}
